//
//  LYCHomeViewController.m
//  爱鲜蜂
//
//  Created by 廖易诚 on 16/6/17.
//  Copyright © 2016年 itcast. All rights reserved.
//

#import "LYCHomeViewController.h"
#import "LYCHeaderView.h"
#import "AFNetworking.h"
#import "LYCNetworkTool.h"
#import "LYCHomeModel.h"
#import "HomeActivityCell.h"
#import "HomeFooterView.h"
#import "HotSaleModel.h"
#import <AVFoundation/AVFoundation.h>

@interface LYCHomeViewController ()<UITableViewDataSource,UITableViewDelegate,AVCaptureMetadataOutputObjectsDelegate>

///
@property (nonatomic, weak) UITableView *tableView;

/// 图片轮播器数据
@property (nonatomic, strong) NSArray *focus;


///
@property (nonatomic, strong) NSArray *icons;

///
@property (nonatomic, strong) NSArray *activities;

///
@property (nonatomic, strong) LYCHeaderView *headerView;

@property (nonatomic, strong) NSMutableArray *hotSaleDatas;

@property (nonatomic, strong) HomeFooterView *footerView;

/// 输入设备
@property (nonatomic, strong) AVCaptureDeviceInput *input;

/// 输出设备
@property (nonatomic, strong) AVCaptureMetadataOutput *output;

/// 会话
@property (nonatomic, strong) AVCaptureSession *session;


/// line
@property (nonatomic, strong) UIView *line;

/// centerView
@property (nonatomic, strong) UIView *centerView;


@property (nonatomic, strong) NSTimer *timer;




@end

@implementation LYCHomeViewController

- (NSMutableArray *)hotSaleDatas {
    if (!_hotSaleDatas) {
        _hotSaleDatas  = [NSMutableArray array];
    }
    return _hotSaleDatas;
}

- (NSArray *)activities {
    if (!_activities) {
        _activities  = [NSMutableArray array];
    }
    return _activities;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
    [self getData];
    
    

}

#pragma mark - 获取数组
- (void)getData {
    

    [[LYCNetworkTool shareTool] requestMethod:POST urlString:@"http://iosapi.itcast.cn/loveBeen/focus.json.php" params:@{@"call":@(1)} progress:^(NSProgress *downloadProgress) {
        //
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        //
                NSLog(@"%@",responseObject);
        NSLog(@"%@",[NSThread currentThread]);
        
        NSDictionary *data = responseObject[@"data"];
        NSArray *focus = data[@"focus"];
        
        // 将图片轮播器的数据转换成模型
        NSMutableArray *focusM = [NSMutableArray array];
        NSMutableArray *imageGroups = [NSMutableArray arrayWithCapacity:0];
        
        for (NSDictionary *dict in focus) {
            LYCHomeModel *model = [LYCHomeModel homeModelWithDic:dict];
            [focusM addObject:model];
            [imageGroups addObject:model.img];
        }
        self.focus = focusM.copy;
        __weak typeof(self) weakSelf = self;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            weakSelf.headerView.imageGroups = imageGroups.copy;
            
        });
        // 中间
        NSArray *icons = data[@"icons"];
        NSMutableArray *iconsM = [NSMutableArray array];
        for (NSDictionary *dict in icons) {
            LYCHomeModel *model = [LYCHomeModel homeModelWithDic:dict];
            [iconsM addObject:model];
        }
        self.icons = iconsM.copy;
        self.headerView.icons = self.icons;
        NSLog(@"icons = %@",self.icons);
        
        // cell
        NSArray *activities = data[@"activities"];
        NSMutableArray *activitiesM = [NSMutableArray array];
        for (NSDictionary *dict in activities) {
            LYCHomeModel *model = [LYCHomeModel homeModelWithDic:dict];
            [activitiesM addObject:model];
        }
        self.activities = activitiesM.copy;
       
        NSLog(@"activities = %@",self.activities);
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.tableView reloadData];
        });
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        //
        NSLog(@"%@",error);
    }];
    
    
    
    /// 获取新鲜热卖数据
    // http://iosapi.itcast.cn/loveBeen/firstSell.json.php
    [[LYCNetworkTool shareTool] requestMethod:POST urlString:@"http://iosapi.itcast.cn/loveBeen/firstSell.json.php" params:@{@"call":@(2)} progress:^(NSProgress *downloadProgress) {
        
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"responseObject = %@",responseObject);
        NSArray *data = responseObject[@"data"];
        NSArray *hotSaleDatas = [HotSaleModel modelArrayWithArr:data];
        [self.hotSaleDatas addObjectsFromArray:hotSaleDatas];
        NSInteger count = (self.hotSaleDatas.count + 1) /2;
        dispatch_async(dispatch_get_main_queue(), ^{

            HomeFooterView *footerView = [[HomeFooterView alloc] initWithFrame:CGRectMake(0, 0, KWIDTH, count * 190)];
            self.tableView.tableFooterView = footerView;
            self.footerView = footerView;
            self.footerView.datas = self.hotSaleDatas;
        });
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error = %@",error);
    }];
}

#pragma mark - 设置ui
- (void)setupUI {
    self.view.backgroundColor = randomColor;
    UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:tableView];
    self.tableView = tableView;
    tableView.delegate = self;
    tableView.dataSource = self;
    LYCHeaderView *headView = [[LYCHeaderView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen hm_screenWidth], 250)];
    tableView.tableHeaderView = headView;
    self.headerView = headView;
    
  self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_black_scancode"] style:0 target:self action:@selector(scanCode)];
    
    
}


#pragma mark - 二维码扫描
- (void)scanCode {
    
//    1、创建设备会话对象，用来设置设备数据输入
    
    
//    2、获取摄像头，并且将摄像头对象加入当前会话中
//    3、实时获取摄像头原始数据显示在屏幕上
//    4、扫描到二维码/条形码数据，通过协议方法回调
    
    // 创建定时器
    NSTimer *timer = [NSTimer timerWithTimeInterval:0.01 target:self selector:@selector(move) userInfo:nil repeats:YES];
    self.timer = timer;
    NSRunLoop *runLoop = [NSRunLoop mainRunLoop];
    [runLoop addTimer:timer forMode:NSDefaultRunLoopMode];
    
    
    
    // 输入设备
    //    MediaType  AVMediaTypeVideo 摄像   audio 麦克风
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    self.input = [AVCaptureDeviceInput deviceInputWithDevice:device error:NULL];
    
    // 输出设备
    self.output = [[AVCaptureMetadataOutput alloc] init];
    
    // 会话
    self.session = [[AVCaptureSession alloc] init];
    
    if ([self.session canAddInput:self.input]) {
        [self.session addInput:self.input];
    }
    
    if ( [self.session canAddOutput:self.output] ) {
        [self.session addOutput:self.output];
    }
    
    // 设置代理
    [self.output setMetadataObjectsDelegate:self queue:dispatch_get_global_queue(0, 0)];
    
    // 指定元素数据类型
    self.output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode];
    
    // 设置扫描范围
    [self.session setSessionPreset:AVCaptureSessionPreset352x288];
    
    // 开启会话
    [self.session startRunning];
    
    AVCaptureVideoPreviewLayer *layer = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
    layer.frame = self.view.bounds;
    [self.view.layer addSublayer:layer];
    
    UIView *centerView = [[UIView alloc] init];
    centerView.backgroundColor = [UIColor clearColor];
    centerView.bounds = CGRectMake(0, 0, 250, 250);
    centerView.center = self.view.center;
    centerView.alpha = 0.5;
    [self.view addSubview:centerView];
    self.centerView = centerView;
    centerView.layer.borderColor = [UIColor blackColor].CGColor;
    centerView.layer.borderWidth = 3;
    
    
    UIImageView *line = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"yellowlight"]];
    self.line = line;
    line.backgroundColor = [UIColor redColor];
    line.frame = CGRectMake(0, 0, 250, 2);
    [centerView addSubview:line];
    
}

#pragma makr - 实现tableView的数据源方法
// 设置多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.activities.count;
}

// 显示每一个cell的样式
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellID = @"cell";
    
    HomeActivityCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    
    if ( !cell) {
        cell = [[HomeActivityCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    LYCHomeModel *model = self.activities[indexPath.row];
    cell.imageStr = model.img;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 150;
}

- (void)move {
    
    [UIView animateWithDuration:0.05 animations:^{
        CGRect viewFrame = self.line.frame;
        if (viewFrame.origin.y != 200) {
            viewFrame.origin.y += 1;
        }else {
            viewFrame.origin.y = 0;
        }
        
        self.line.frame = viewFrame;
        
    }];
    
}

// 实现代理方法
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
    
    AVMetadataMachineReadableCodeObject *obj = [metadataObjects firstObject];
    
    NSLog(@"%@",obj.stringValue);
    
    [self.session stopRunning];
    
    [self.timer invalidate];
    self.timer = nil;
    
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
